import keyMirror from 'keymirror';
import { combineReducers } from 'redux'
import axios from 'axios';

const userState = keyMirror({
    NOT_LOGINED: null,
    LOGINED: null
});

const initialState = {
    loginState: window.sessionStorage.getItem('loginState') ? window.sessionStorage.getItem('loginState') : userState.NOT_LOGINED,
    session: {
        userid: window.sessionStorage.getItem('userid') ? window.sessionStorage.getItem('userid') : '',
        username: window.sessionStorage.getItem('nickname') ? window.sessionStorage.getItem('nickname') : ''
    }
};

const getIsLogined = loginState => (
    loginState === userState.LOGINED
);

const reducer = function (state, action) {
    if (typeof state === 'undefined') state = initialState;
    switch (action.type) {
        case 'LOGINED':
            if(!(action.yeslogin.username && action.yeslogin.userpswd)){
                return false
            }
            var data = {
                "username": action.yeslogin.username,
                "userpswd": action.yeslogin.userpswd
            };
            axios.post('http://127.0.0.1:5000/login',data)
            // axios.post('./login',data)
            .then((response) => { 
                if (response.data.code == 200) {
                    // 
                    window.sessionStorage.setItem('userid',response.data.userinfo.uid)
                    window.sessionStorage.setItem('nickname',response.data.userinfo.nickname)
                    window.sessionStorage.setItem('loginState','LOGINED')
                }
            })
            return { 
                // loginState: userState.LOGINED,
                loginState: window.sessionStorage.getItem('loginState'),
                session: {
                    userid: window.sessionStorage.getItem('userid'),
                    username: window.sessionStorage.getItem('nickname'),
                }
            }; 
            // 
        default:
            return state;
    }
}
// 
export {
    reducer as default,
    initialState as userStateInitialState,
    userState,
    getIsLogined
};
